<?php
/**
 * Created by PhpStorm.
 * User: krystal
 * Date: 2019/3/1
 * Time: 15:49
 */

namespace app\common\model;

use think\Cache;

/**
 * 课程评论评论模型
 * Class ZhunleCourseComment
 * @package app\common\model
 */
class ZhunleCourseComment extends Base
{
    protected $table = 'wechat_backup_07_18_14_43_00.zhunle_course_comment';

    const COURSE_COMMENT_IDS = 'course:comment:cid:';//当前课程所有的评论id
    const COURSE_COMMENT_UID = ':user:course:comment:';//当前用户的所有评论id
    const COURSE_COMMENT_SCORE = 'course:comment:score:';//当前课程平均评论分数
    const COURSE_COMMENT_INFO_ID = 'course:comment:info:';//当前评论的详情
    const CACHE_TIME = 86400 * 7;

    /**
     * 删除评论相关缓存
     * @param array $map
     */
    public function rm_cache($map = [])
    {
        $course_id = $map['course_id'] ?? 0;
        $comment_id = $map['comment_id'] ?? 0;
        $uid = $map['uid'] ?? 0;
        $type = $map['type'] ?? 0;//1=>增加,2=>编辑

        switch ($type)
        {
            case 1:
                Cache::rm(self::COURSE_COMMENT_IDS . $course_id);
                Cache::rm($uid . self::COURSE_COMMENT_UID);
                break;
            case 2:
                Cache::rm(self::COURSE_COMMENT_INFO_ID . $comment_id);
                break;
        }

        Cache::rm(self::COURSE_COMMENT_SCORE . $course_id);
    }

    /**
     * 获取当前课程的所有评论分数,用于计算平均评论分数
     * @param array $map
     * @return bool|false|mixed|\PDOStatement|string|\think\Collection
     */
    public function getCourseCommentScore($map = [])
    {

        $id = $map['id'];

        $data = false;

        if ($this->cache_on >= 1)
        {
            $data = Cache::get(self::COURSE_COMMENT_SCORE . $id);
        }

        // 获取所有课程评论id
        if ($data === false)
        {
            $where = [
                'status' => 0,
                'cid' => $id
            ];

            try
            {
                $data = $this
                    ->field('score')
                    ->where($where)
                    ->order('create_time', 'DESC')
                    ->select();
                $data = json_decode(json_encode($data, true), true);

                // 缓存课程评论评论id,根据课程评论id
                if ($this->cache_on >= 1)
                {
                    Cache::set(self::COURSE_COMMENT_SCORE . $id, $data, self::CACHE_TIME);
                }

            }
            catch (\Exception $e)
            {
                $this->error = '获取上架课程的评分失败';
                return false;
            }

        }

        return $data;

    }

    /**
     * 获取某一个课程的所有评论信息
     * @param array $map
     * @return array
     */
    public function getCourseComment($map = [])
    {
        $id = $map['id'];
        $page = $map['page'];

        $all_course_section_comment_ids = false;

        if ($this->cache_on >= 1)
        {
            $all_course_section_comment_ids = Cache::get(self::COURSE_COMMENT_IDS . $id);
        }

        // 获取所有课程评论id
        if ($all_course_section_comment_ids === false)
        {
            $where = [
                'status' => 0,
                'cid' => $id
            ];

            try
            {
                $data = $this
                    ->where($where)
                    ->order('create_time', 'DESC')
                    ->column('id');

                // 将课程评论评论id组成字符串
                if (!empty($data))
                {
                    $all_course_section_comment_ids = implode(',', $data);
                }

                // 缓存课程评论评论id,根据课程评论id
                if ($all_course_section_comment_ids && $this->cache_on >= 1)
                {
                    Cache::set(self::COURSE_COMMENT_IDS . $id, $all_course_section_comment_ids, self::CACHE_TIME);
                }

            }
            catch (\Exception $e)
            {
                $this->error = '获取上架的课程评论基本信息失败';

                return false;
            }

        }

        // 将课程评论id转为数组
        $all_course_section_comment_ids = explode(',', $all_course_section_comment_ids);

        $per_page = 10;// 当前文章评论每页显示数量

        // 统计有多少课程评论
        $total = count($all_course_section_comment_ids);
        //获取数据分页信息
        $data_list = getPaginatorData($total, $page, $per_page);

        //获取分页后的课程评论id数组
        $all_course_section_comment_id = array_slice($all_course_section_comment_ids, $data_list['start'], $per_page);

        unset($data_list['start']);
        unset($data_list['end']);


        // 根据当前页课程评论评论id获取所需的课程评论评论信息
        if (!empty($all_course_section_comment_id))
        {
            $ac_ids = '';
            $temp = [];

            // 获取缓存的课程评论评论内容,根据课程评论评论id
            foreach ($all_course_section_comment_id as $ac_id)
            {
                if ($this->cache_on >= 1)
                {
                    // 根据课程评论评论id 获取课程评论评论内容
                    $temp[$ac_id] = Cache::get(self::COURSE_COMMENT_INFO_ID . $ac_id);
                } else
                {
                    // 缓存未开启时，默认从数据库获取
                    $temp[$ac_id] = false;
                }
                // 课程评论评论内容未缓存，等待从数据库中获取
                if ($temp[$ac_id] === false && $ac_id)
                {
                    $ac_ids .= $ac_id . ',';
                }
            }

            // 从数据库获取课程评论评论内容
            if ($ac_ids != '' || strlen($ac_ids) > 0)
            {
                //去掉结尾的 ，
                $ac_ids = substr($ac_ids, 0, strlen($ac_ids) - 1);

                try
                {
                    $data = $this
                        ->field('id,uid,status,cid,score,content,create_time')
                        ->where('status', 0)
                        ->where('id in(' . $ac_ids . ')')
                        ->order('create_time', 'DESC')
                        ->select();

                    $course = json_decode(json_encode($data, true), true);

                }
                catch (\Exception $e)
                {
                    $this->error = '获取课程评论的基本信息失败';
                    return false;
                }

                if (!empty($course))
                {
                    foreach ($course as $c)
                    {
                        // 将课程评论评论内容缓存
                        if ($this->cache_on >= 1)
                        {
                            Cache::set(self::COURSE_COMMENT_INFO_ID . $c['id'], $c, self::CACHE_TIME);
                        }
                        // 将数据库查出来的内容 写入到数组中为空的部分
                        if ($c)
                        {
                            $temp[$c['id']] = $c;
                        }
                    }
                }
            }

            foreach ($temp as $item)
            {
                if ($item)
                {
                    $data_list['data'][] = $item;
                }
            }
        }

        return $data_list;

    }

    /**
     * 获取当前用户的所有评论信息
     * @param array $map
     * @return array|bool
     */
    public function getUserCommentInfo($map = [])
    {
        $uid = $map['uid'];

        $data_list = [];

        $user_comment_ids = false;

        if ($this->cache_on >= 1)
        {
            $user_comment_ids = Cache::get($uid . self::COURSE_COMMENT_UID);
        }
        // 获取所有课程评论id
        if ($user_comment_ids === false)
        {
            $where = ['uid' => $uid];
            try
            {
                $data = $this
                    ->where($where)
                    ->column('id');
                // 将课程评论评论id组成字符串
                if (!empty($data))
                {
                    $user_comment_ids = implode(',', $data);
                }

                // 缓存课程评论评论id,根据课程评论id
                if ($user_comment_ids && $this->cache_on >= 1)
                {
                    Cache::set($uid . self::COURSE_COMMENT_UID, $user_comment_ids, self::CACHE_TIME);
                }

            }
            catch (\Exception $e)
            {
                $this->error = '获取当前用户的评论信息失败.';
                return false;
            }

        }
        // 将课程评论id转为数组
        $user_comment_ids = explode(',', $user_comment_ids);

        // 根据当前页课程评论评论id获取所需的课程评论评论信息
        if (!empty($user_comment_ids))
        {
            $ac_ids = '';
            $temp = [];

            // 获取缓存的课程评论评论内容,根据课程评论评论id
            foreach ($user_comment_ids as $ac_id)
            {
                if ($this->cache_on >= 1)
                {
                    // 根据课程评论评论id 获取课程评论评论内容
                    $temp[$ac_id] = Cache::get(self::COURSE_COMMENT_INFO_ID . $ac_id);
                } else
                {
                    // 缓存未开启时，默认从数据库获取
                    $temp[$ac_id] = false;
                }
                // 课程评论评论内容未缓存，等待从数据库中获取
                if ($temp[$ac_id] === false && $ac_id)
                {
                    $ac_ids .= $ac_id . ',';
                }
            }

            // 从数据库获取课程评论评论内容
            if ($ac_ids != '' || strlen($ac_ids) > 0)
            {
                //去掉结尾的 ，
                $ac_ids = substr($ac_ids, 0, strlen($ac_ids) - 1);

                try
                {
                    $data = $this
                        ->field('id,uid,status,cid,score,content,create_time')
                        ->where('id in(' . $ac_ids . ')')
                        ->order('create_time', 'DESC')
                        ->select();

                    $course = json_decode(json_encode($data, true), true);

                }
                catch (\Exception $e)
                {
                    $this->error = '获取课程评论的基本信息失败';
                    return false;
                }

                if (!empty($course))
                {
                    foreach ($course as $c)
                    {
                        // 将课程评论评论内容缓存
                        if ($this->cache_on >= 1)
                        {
                            Cache::set(self::COURSE_COMMENT_INFO_ID . $c['id'], $c, self::CACHE_TIME);
                        }
                        // 将数据库查出来的内容 写入到数组中为空的部分
                        if ($c)
                        {
                            $temp[$c['id']] = $c;
                        }
                    }
                }
            }
            foreach ($temp as $item)
            {
                if ($item)
                {
                    $data_list[] = $item;
                }
            }
        }
        return $data_list;
    }

    /**
     * 获取当前评论信息
     * @param array $map
     * @return array|bool
     */
    public function getCommentInfo($map = [])
    {
        $id = $map['id'];

        $data = false;
        if ($this->cache_on >= 1)
        {
            $data = Cache::get(self::COURSE_COMMENT_INFO_ID . $id);
        }
        if ($data === false)
        {
            $where = [
                'status' => 0,
                'id' => $id
            ];
            try
            {
                $data = $this
                    ->field('id,uid,status,cid,score,content,create_time')
                    ->where($where)
                    ->order('create_time', 'DESC')
                    ->findOrFail()
                    ->toArray();
            }
            catch (\Exception $e)
            {
                $this->error = '获取课程评论的基本信息失败';
                return false;
            }
        }

        return $data;
    }

    /**
     * 添加评论相关模型
     * @param int $uid 用户id
     * @param int $cid 课程id
     * @param array $data
     * @return bool|int
     */
    public function save_data($uid = 0, $cid = 0, $data = [])
    {
        try
        {
            $id = $this->insertGetId($data);
            //删除评论相关缓存
            $this->rm_cache(['course_id' => $cid, 'uid' => $uid, 'type' => 1]);
        }
        catch (\Exception $e)
        {
            $this->error = '添加评论失败';
            return false;
        }
        return $id;
    }

    /**
     * 更新评论信息
     * @param int $id 评论id
     * @param array $data
     * @return bool
     */
    public function update_data($id = 0, $data = [])
    {
        try
        {
//            $this->where(['id'=>$id])->update($array);
            self::update($data, ['id' => $id]);

            //获取当前评论所属的课程id
            $CourseCommentInfo = $this->getCommentInfo(['id' => $id]);
            //删除评论相关缓存
            $this->rm_cache(['comment_id' => $id, 'course_id' => $CourseCommentInfo['cid'], 'type' => 2]);
        }
        catch (\Exception $e)
        {
            $this->error = '编辑评论失败';
            return false;
        }
        return true;
    }
}
